﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Machinery.Cogs.Interfaces;

namespace Machinery.Cogs
{
    /// <summary>
    /// Wrapper for WebRequest.Create. 
    /// </summary>
    public class WebRequestCog : IWebRequestCog
    {
        public virtual string DoPostRequest(string url, string data, int timeout)
        {
            var request = WebRequest.Create(url) as HttpWebRequest;
            request.Timeout = timeout;
            request.Method = "POST";
            request.ContentLength = data.Length;

            using (var streamWriter = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
            {
                streamWriter.Write(data);
            }

            var response = (HttpWebResponse)request.GetResponse();

            string result;
            var responseStream = response.GetResponseStream();
            using (var streamReader = new StreamReader(responseStream))
            {
                result = streamReader.ReadToEnd();
            }
            return result;    
        }
    }
}